package org.charry.lib.config.impl;

import java.sql.SQLException;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.charry.lib.config.Config;
import org.charry.lib.config.ConfigValue;

import org.charry.lib.database_utility.DatabaseFactory;
import org.charry.lib.database_utility.DatabaseFactory.ResultSetEx;

public class DatabaseConfig implements Config {
	private static Log log = LogFactory.getLog(DatabaseConfig.class);
	private static HashMap<String, String> configItemHashMap = new HashMap<String, String>();
	private static long lastCheckPoint = 0;
	private static int EXPIRE_OFFSET = 1 * 3600 * 1000;
	private String configTable = "";
	private String databaseAlias = "";

	public DatabaseConfig(final String databaseAlias, final String configTable) {
		this.databaseAlias = databaseAlias;
		this.configTable = configTable;

		loadConfig();
	}

	private void reloadConfig() {
		long lNow = new java.util.Date().getTime();

		if (lNow - lastCheckPoint > EXPIRE_OFFSET)
			loadConfig();
	}

	public String getConfig(String item) {
		reloadConfig();

		return configItemHashMap.get(item);
	}

	private HashMap<String, String> loadConfig() {
		if (configItemHashMap != null)
			configItemHashMap.clear();

		String sql = "SELECT * FROM " + configTable;
		ResultSetEx rx = null;
		configItemHashMap.clear();

		try {
			rx = DatabaseFactory.getInstance(databaseAlias).executeQueryEx(sql);
			while (rx.getResultSet().next()) {
				configItemHashMap.put(rx.getResultSet().getString("NAME")
						.trim(), rx.getResultSet().getString("VALUE").trim());
			}
		} catch (SQLException e) {
			log.error("failed to get config from database:" + e);
		} finally {
			rx.close();
		}

		log.info("load config from database:" + databaseAlias);

		return configItemHashMap;
	}

	public ConfigValue getKonfig(String item) {
		return new ConfigValue(this.getConfig(item));
	}
}
